package com.srb.core.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.srb.common.exception.BusinessException;
import com.srb.common.result.R;
import com.srb.common.result.ResponseEnum;
import com.srb.core.pojo.dto.ExcelDictDTO;
import com.srb.core.pojo.entity.Dict;
import com.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author dapeng
 * @since 2021-08-08
 */
@Api(tags = {"数据字典管理"})
@Slf4j
@RestController
@RequestMapping("/admin/core/dict")
//@CrossOrigin
public class AdminDictController {

    @Autowired
    private DictService dictService;

    @ApiOperation(value = "excel数据的批量导入")
    @PostMapping(value = {"/import"})
    public R batchImport(
            @ApiParam(value = "excel数据字典文件",required = true)
            @RequestParam(value = "file") MultipartFile file){
        try {
            InputStream inputStream = file.getInputStream();
            dictService.importData(inputStream);
            return R.ok().message("数据字典批量导入成功");
        }catch (Exception e){
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation(value = "excel数据导出")
    @GetMapping(value = {"/export"})
    public void download(HttpServletResponse response)throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("mydict","UTF-8").replaceAll("\\+","%20");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("模板").doWrite(dictService.listDictData());
    }

    @ApiOperation(value = "根据上级节点id获取子节点数据列表")
    @GetMapping(value = {"/listByParentId/{parentId}"})
    public R listByParentId(@ApiParam(value = "上级节点id",required = true)@PathVariable(value = "parentId") Long parentId){
        List<Dict> list = dictService.listByParentId(parentId);
        return R.ok().data("list",list);
    }
}
